package com.cy.law.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: caiqyxyx
 * @Date: 2018/8/27 14:09
 * 基础过滤类
 */
public class BaseFilter implements Filter {
    private FilterConfig config;
    private String allowOrigin;

    public BaseFilter() {
    }

    public BaseFilter(String allowOrigin) {
        this.allowOrigin = allowOrigin;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String myOrigin = ((HttpServletRequest) servletRequest).getHeader("origin");
        response.addHeader("Access-Control-Allow-Origin", myOrigin);
        response.addHeader("Access-Control-Allow-SyncMethods", "*");
//        response.addHeader("Access-Control-Allow-Headers", "*");
        response.addHeader("Access-Control-Allow-Headers", "content-type,session-token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        this.config = null;
    }
}